import React from 'react'
import { Input, Icon, Row, Col } from 'antd'
import '../../less/index.less'
import { Link, withRouter } from 'react-router-dom'

class EditableCell extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      value: this.props.value,
      editable: false
    }
  }

  handleChange (e) {
    let value = e.target.value
    this.setState({value})
  }

  check () {
    this.setState({editable: false})
    if (this.props.onChange) {
      this.props.onChange(this.state.value)
    }
  }

  edit () {
    this.setState({editable: true})
  }

  render () {
    const {value, editable} = this.state
    const linkUrl = this.props.linkUrl || ''
    return (
      <Row>
        <Col span={22} className='col'>
          {editable
            ? <Input
              value={value}
              onChange={this.handleChange.bind(this)}
              onPressEnter={this.check.bind(this)} />
            : linkUrl
              ? <Link to={linkUrl} className='link-text'>
                <div className='editable-cell-preview '>{value}</div>
              </Link>
              : <div className='editable-cell-preview '>{value}</div>
          }
        </Col>
        {
          this.props.isReadOnly
            ? ''
            : <Col span={1} offset={1}>
              {editable
                ? <Icon
                  type='check'
                  onClick={this.check.bind(this)} />
                : <Icon
                  type='edit'
                  onClick={this.edit.bind(this)} />
              }
            </Col>
        }

      </Row>
    )
  }
}

export default withRouter(EditableCell)
